package com.aliyun.heiyu.common.util;

import java.nio.charset.StandardCharsets;

import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.util.encoders.Hex;

/**
 * 国密散列算法
 *
 * @author henry
 *
 */
public abstract class SM3Util {

    /**
     * 对字符串编码
     * @param str
     * @return 64位Hex串
     */
    public static String encodeToString(String str) {
        return encodeToString(str.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 对数据编码
     * @param data
     * @return 64位Hex串
     */
    public static String encodeToString(byte[] data) {
        return new String(Hex.encode(encode(data)), StandardCharsets.UTF_8).toUpperCase();
    }

    public static String convertEncryption(String str){
        return encodeToString(str);
    }

    /**
     * 对数据编码
     * @param data
     * @return
     */
    public static byte[] encode(byte[] data) {
        byte[] md = new byte[32];

        byte[] bytes = new byte[data.length];
        System.arraycopy(data, 0, bytes, 0, data.length);

        SM3Digest digest = new SM3Digest();

        digest.update(bytes, 0, bytes.length);

        digest.doFinal(md, 0);

        return md;
    }
}